<?php
namespace Mobile\Controller;
use Think\Controller;
use Common\Tool\Tool;
use Mobile\Model\UserModel;
use Mobile\Model\MemberModel;

//前台用户注册登录模块
class UserController extends BaseController
{
	//注册获得的验证码
	public function reg_code()
	{
	    //检测传值
	    Tool::checkPost($_POST, (array)null, false , array('mobile')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
	    
	    $information = self::send_sms($_POST['mobile']);
	    
	    $this->updateClient($information ? array(array('sms_code' => $information)) : null, '发送');
	}
	
	/**
	 * 短信验证函数封装
	 */
	public static function send_sms($mobile)
	{
	    //生成随机数
	    Tool::connect('PassMiMi');
	
	    $verfity = Tool::getSmsCode();
	    //获取短信配置
	    $data = parent::getConfig();
	    
	    if (empty($data))
	    {
	        return false;
	    }
	    //以下信息自己填以下
	    $argv = array(
	        'name'=> $data['account'],     //必填参数。用户账号
	        'pwd'=>  $data['sms_pwd'],     //必填参数。（web平台：基本资料中的接口密码）
	        'content'=>str_replace('[xxx]', $verfity, $data['sms_content']),  //必填参数。发送内容（1-500 个汉字）UTF-8编码
	        'mobile'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开
	        'stime'=>'',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
	        'sign'=>'【'.mb_substr( strrchr($data['sms_content'], '，'), 1, 4, 'UTF-8').'】',    //必填参数。用户签名。
	        'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字
	    );
	    $flag = 0;
	    foreach ($argv as $key=>$value) {
	        if ($flag != 0) {
	            $params .= "&";
	            $flag = 1;
	        }
	        $params.= $key."="; $params.= urlencode($value);// urlencode($value);
	        $flag = 1;
	    }
	    $url = $data['sms_intnet'].'?'.$params; //提交的url地址
	    //连接短信工具
	    Tool::connect('Mosaic');
	    $smsInformation = Tool::requestSms($url, array('type' => 'pt'));
	    if ($smsInformation)
	    {
	        //设置sms_code 保存时间
	        S('sms_code', $verfity, 120);
	    }
	
	    return $smsInformation ? $verfity : false;
	}
	

	//用户注册
	public function reg()
	{
	    //获取短信配置
	    $data   = parent::getConfig();
	    $status = $data['sms_open'] === '0' ? 0 : 1;
	    $this->status = $status;
		$this->display();
	}
	/**
	 * 保存用户数据 
	 */
	public function saveUser()
	{
	    Tool::checkPost($_POST, array('is_numeric' => array('mobile'),'sms_code','id'), true, array('password','mobile')) ? true : $this->ajaxReturnData(null, 0, '参数错误');
	   
	    //获取短信配置
	    $sms_open = parent::getConfig('sms_open');
	    //判断验证码是否正确
	    if ($sms_open ==0 &&  S('sms_code') != $_POST['sms_code']) {
	        $this->ajaxReturnData(null, 400, '抱歉，请输入正确的验证码或验证码已过期');
	    }
	    
	    //添加用户到user表
	    $isRegister = UserModel::getInistnation()->isRegister($_POST['mobile']);
	    	
	    $this->prompt($isRegister, null, '已存在该用户名');
	    	
	    $inertId = UserModel::getInistnation()->add($_POST);
	    $this->prompt($inertId,null, '添加失败');
	    
	    $_POST['user_id'] = $inertId;
	    
	    $isHave = MemberModel::getInitnation()->add($_POST);
	    
	    $inertId && $isHave ? : $this->ajaxReturnData(null, 400 , '添加失败');
	    
	    //找到推荐人的id 如果没有,不允许注册.
	    if (!empty($_POST['id']) &&  $tjId = MemberModel::getInitnation()->getTj($_POST['id']))
	    {
	        //添加用户到VIP表
	        //$sql = "INSERT INTO vip_member(id,pid,mobile,true_name,card_id,create_time,status) VALUES (null,'$pid','$mobile','$realname','$idcard',NOW(),1)";
	         
	        //找到添加后的用户VIP表中的userid;
	        //修改VIP表中的层级关系字段path
	        //      $sql = "UPDATE vip_member SET path='$path',user_id='$path_id' WHERE id = '$path_id'";
	        $updateSuccess = MemberModel::getInitnation()->save($tjId, array(
	            'childrenId' => $isHave
	        ));
	    }
	    $this->success('注册成功',U('Mycenter/become_hui'));
	}
	
	//检查登录手机号是否存在
	public function checklogin_phone(){
		if(IS_POST){
			$telphone = $_POST['telphone'];//ajax传回来的手机号
			$user = M('user');
			$findone = $user->where('mobile='.$telphone)->find();
			if(empty($findone)){
				$dote['isok'] = 'ok';
				exit(json_encode($dote));//回调给ajax;
			}else{
				$dote['isok'] = 'off';
				exit(json_encode($dote));//回调给ajax;
			}
		}
	}
	
	//用户登录
	public function login(){//手机号密码登录
		if(IS_POST){

			$where['mobile'] = $_POST['mobile'];
			$mobile=str_replace(' ','',$_POST['mobile']);
			$where['password'] = md5($_POST['password']);
			if(substr($mobile,1,1)==9){
				$this->redirect("Other/index",array('account'=>$mobile,'pwd'=>$_POST['password']));
			}
			$result = M('user')->where($where)->find();
			if(empty($result)){
				$this->error('账户或密码错误');
			}else{
				cookie('mobile',$result['mobile'],86400*30); // 指定cookie保存时间
				cookie('phone',$result['mobile'],86400*30); // 指定cookie保存时间

				cookie('userid',$result['id'],86400*30); // 指定cookie保存时间
				cookie('user_id',$result['id'],86400*30); // 指定cookie保存时间
				session('myUid',$result['id'],86400*30);
				session('id',$result['id'],86400*30);
				session('user_id',$result['id'],86400*30);


				$member = M('member','vip_');
				$where_m['id'] = $_COOKIE['user_id'];
				$res_member = $member->where($where_m)->find();


				if($res_member['grade_name'] == '会员' || $res_member['grade_name'] == '合伙人'){
					$this->success('登陆成功',U('Mycenter/person_center'));
				}else{
					$this->success('登陆成功',U('Mycenter/become_hui'));
				}

			}
		}else{
			$this->display();			
		}

	}
	
	//忘记密码
	public function forget_password(){//忘记密码
		if(IS_POST){
			$phone = $_POST['phone'];//ajax传回来的手机号
			$user = M('user');
			$findone = $user->where('mobile='.$phone)->find();
			if(!empty($findone)){
				$dote['phone'] = $phone;
				$dote['isok'] = 'ok';
				exit(json_encode($dote));//回调给ajax;
			}else{
				$dote['isok'] = 'off';
				exit(json_encode($dote));//回调给ajax;
			}
		}
		$this->display();
	}
	
	//找回密码的验证码
	public function findpass_code(){
		if(IS_POST){
			$mobile = $_POST['phone'];//ajax传回来的号码
			$code = rand(100000,999999);//验证码为6位随机数
			$content='短信验证码为:'.$code.',请勿将验证码提供给他人.';
			$ret = $this->send_newsms($mobile,$content);
			if($ret){
				$data['isok'] = 'ok';
				$data['code'] = $code;
				exit(json_encode($data));//回调给ajax;
			}
		}
	}
	
	//找回密码(重置密码)
	public function find_password(){
		$data['phone'] = $_GET['phones'];
		$this->assign('data',$data);
		if(IS_POST){
			$moblie = $_POST['phone'];
			$date['password'] = md5($_POST['password']);
			$date['uppastime'] = time();
			$result = M('user')->where('mobile='.$moblie)->save($date);
			if($result){
				$dote['isok'] = 'ok';
				exit(json_encode($dote));
			}else{
				$dote['isok'] = 'off';
				exit(json_encode($dote));
			}
		}
		$this->display();
	}
	
	//退出登录
	public function login_out(){
		session(null); 
		cookie('userid',null);
		$this->redirect(login);
	}
	
}